#!/usr/bin/python
import socket
import time
from urllib import request
from Msg.douyu_msg import DouyuMsg
from Msg.douyu_msg_parser import parse_recv_msg

HOST = 'openbarrage.douyutv.com'
PORT = 8601
# 输入房间地址，获取房间号码
url = "https://www.douyu.com/549378"
roomName = url.replace("https://www.douyu.com/","")
response = request.urlopen('http://open.douyucdn.cn/api/RoomApi/room/' + roomName)
roojson = response.read().decode("utf-8")

# print(roojson)
# print(type(roojson))
roomid = eval(roojson)['data']['room_id']
room_status = eval(roojson)['data']['room_status']
print("RoomID:" + roomid)
# 与斗鱼的第三方弹幕服务器连接
# roomid='104871'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 定义socket类型，网络通信，TCP
s.connect((HOST, PORT))  # 要连接的IP与端口

cmd = DouyuMsg("type@=loginreq/roomid@=" + roomid + "/").get_bytes()
s.sendall(cmd)  # 把命令发送给对端
data = s.recv(1024)  # 把接收的数据定义为变量
# print(data)  # 输出变量
unixTime = time.time()  # 初始化时间戳
while 1:
    if time.time() - unixTime > 30:  # 如果时间超过30s，发送一个心跳信息保持在线
        unixTime = time.time()
        cmd = DouyuMsg("type@=keeplive/tick@=" + str(int(unixTime)) + "/").get_bytes()
        s.sendall(cmd)  # 把命令发送给对端
    cmd = DouyuMsg("type@=joingroup/rid@=" + roomid + "/gid@=-9999/").get_bytes()
    s.sendall(cmd)  # 把命令发送给对端
    data = s.recv(1024)  # 把接收的数据定义为变量
    # print(data[12:-1].decode('utf-8', 'ignore'))
    parse_recv_msg(data[12:-1].decode('utf-8', 'ignore'))
    # ArrData = data.split(b'/')
    # print(ArrData[0].split(b'@=')[1])
    # if ArrData[0].split(b'@=')[1] == b'chatmsg':
    #     print(ArrData[4].decode("utf-8").split("@=")[1] + ":" + ArrData[5].decode("utf-8").split("@=")[1])
    # elif ArrData[0].split(b'@=')[1] == b'onlinegift': # 鱼丸暴击
    #     pass
    # elif ArrData[0].split(b'@=')[1] == b'dgb': # 礼物
    #     pass
    # elif ArrData[0].split(b'@=')[1] == b'uenter': # 人员进出
    #     pass
    # elif ArrData[0].split(b'@=')[1] == b'bc_buy_deserve': #酬勤
    #     pass
    # elif ArrData[0].split(b'@=')[1] == b'ul_ranklist':
    #     pass
    # elif ArrData[0].split(b'@=')[1] == b'ranklist':
    #     pass
    # elif ArrData[0].split(b'@=')[1] == b'ruclp':
    #     pass
    # else:
    #     print(ArrData)
    #     print("未知类型，退出弹幕........")
    #     break

s.close()  # 关闭连接
